<template>
	<view class="schedule_add_or_edit">
		<uni-forms :modelValue="formData" ref="form" :rules="rules" :label-width="77">
			<uni-forms-item label="标题" name="title" required>
				<uni-easyinput v-model="formData.title" placeholder="请输入标题"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="开始时间" name="myDate" required>
				<view style="display: flex;justify-content: space-between;width: 100%;align-items: center;" @click="showTime = true">
					<view style="width: 100%;display: flex;gap:10rpx;flex-direction: column;">
						<uni-easyinput disabled v-model="formData.myDate" placeholder="请选择开始时间"
							style="pointer-events: none;"></uni-easyinput>
						<uni-easyinput disabled v-model="formData.endDate" placeholder="请选择结束时间"
							style="pointer-events: none;"></uni-easyinput>
					</view>
					<uni-icons type="down"></uni-icons>
				</view>
			</uni-forms-item>
			<uni-forms-item label="是否完成" v-if="isUpdate != 0">
				<switch color="#0097ff" :checked="formData.closed" @change="(e) => formData.closed = e.detail.value"></switch>
			</uni-forms-item>
			<uni-forms-item label="是否共享">
				<switch color="#0097ff" :checked="formData.shared" @change="(e) => formData.shared = e.detail.value"></switch>
			</uni-forms-item>
			<uni-forms-item label="是否提醒" v-if="isUpdate != 2">
				<switch color="#0097ff" :checked="formData.remind" @change="(e) => formData.remind = e.detail.value"></switch>
			</uni-forms-item>
			<uni-forms-item label="提醒时间" prop="beforeName" required v-if="formData.remind">
				<view style="display: flex;justify-content: space-between;width: 100%;align-items: center;height: 100%;" @click="handleShowBefore">
					<view>{{ formData.beforeName }}</view>
					<uni-icons type="down"></uni-icons>
				</view>
			</uni-forms-item>
			<uni-forms-item label="将日程分配给" prop="mine" required v-if="isUpdate != 2">
				<view style="width: 100%;">
					<view style="display: flex;gap:20rpx;align-items: center;">
						<l-checkbox @update:modalValue="formData.mine = $event" :modalValue="formData.mine"
							textBefore="自己"></l-checkbox>
						<l-checkbox @update:modalValue="formData.others = $event" :modalValue="formData.others"
							textBefore="他人"
							:disabled="isUpdate == 1 && formData.others && !isMultiDeptistUserRealNames"></l-checkbox>
						<view>
							<button size="mini" @click="handleSelectUser" v-if="formData.others">选择</button>
						</view>
					</view>
					<view v-if="formData.others"
						style="width:100%;max-height: 150rpx;overflow-y: auto;display: flex;gap: 10rpx;flex-wrap: wrap;align-items: center;">
						<view
							style="display: flex;gap:10rpx;border: 1px solid #a0cfff;padding: 0 14rpx;border-radius: 6rpx;cursor: pointer;align-items: center;background-color: #ecf5ff;color: #2979ff;font-size: 28rpx;"
							v-for="(item, index) in formData['hadUsers']" :key="item.key">{{ item.title }}
							<view>
								<uni-icons type="closeempty" @click="handleCloseTag(index)" color='#2979ff'
									size="14"></uni-icons>
							</view>
						</view>
					</view>
				</view>
			</uni-forms-item>
			<uni-forms-item label="内容" prop="content" required>
				<uni-easyinput type="textarea" v-model="formData.content" placeholder="请输入内容"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item label="创建者" v-if="formData.distributer">
				<view style="height: 100%;display: flex;align-items: center;">
					{{ formData.distributer || '' }}
				</view>
			</uni-forms-item>
			<uni-forms-item label="附件">
				<FileUpload ref="fileUploadRef" :isUpdate='isUpdate' type="plan" />
			</uni-forms-item>
		</uni-forms>
		<view style="margin: 10rpx 0;">
			注: 日程修改时，如果是分配给他人的，不联动修改
		</view>
		<button @click="submit" type="default" class="cus_button" v-if="isUpdate != 2">保存</button>

		<TkiTree idKey="value" rangeKey="label" :range="beforeList" ref="showBeforeRef" @confirm="handleConfirmBefore"
			:multiple="false" />
		<MxDatepicker format="yyyy-mm-dd hh:ii:ss" type="rangetime" :show="showTime" :value="times" :show-tips="true"
			:begin-text="'开始时间'" :end-text="'结束时间'" :show-seconds="true" @confirm="handleConfirmTime"
			@cancel="showTime = false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
	</view>
</template>

<script setup>
import {
	ref,
	computed
} from 'vue'
import {
	postFormAction
} from "@/utils/request.js";
import MxDatepicker from '../component/mx-datepicker/mx-datepicker'
import SelectUser from '@/components/selectUser/index.vue'
import FileUpload from '../component/file-upload/file-upload.vue'
import TkiTree from '@/components/tki-tree/tki-tree.vue'
import {
	onReady,
	onShow,
	onLoad
} from '@dcloudio/uni-app'

const url = {
	getPlan: '/plan/getPlan',
	create: '/plan/create',
	update: '/plan/update',
}
// 表单数据
const formData = ref({
	title: '',
	hadUsers: []
})
const rules = {
	title: {
		rules: [{
			required: true,
			errorMessage: '请输入标题',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}]
	},
	beforeName: {
		rules: [{
			required: true,
			errorMessage: '请选择提醒时间',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}]
	},
	myDate: {
		rules: [{
			required: true,
			errorMessage: '请选择时间范围',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}]
	},
	content: {
		rules: [{
			required: true,
			errorMessage: '请输入内容',
			// 可以单个或者同时写两个触发验证方式 
			trigger: ['change', 'blur'],
		}]
	},
}
const isUpdate = ref(1) //1编辑 0新增 2是详情
const isMultiDeptistUserRealNames = ref(false)
const mainModel = ref({})
const showTime = ref(false)
const times = ref([])
const beforeList = [{
	label: '十分钟',
	value: 10,
},
{
	label: '二十分钟',
	value: 20,
},
{
	label: '三十分钟',
	value: 30,
},
{
	label: '四十五分钟',
	value: 45,
},
{
	label: '一小时',
	value: 60,
},
{
	label: '二小时',
	value: 120,
},
{
	label: '三小时',
	value: 180,
},
{
	label: '四小时',
	value: 240,
},
{
	label: '五小时',
	value: 300,
},
{
	label: '六小时',
	value: 360,
},
{
	label: '十二小时',
	value: 720,
},
]
const fileUploadRef = ref(null)
const ishadSelect = computed(() => formData.value.mine || formData.value.others)
// const beforeName = computed(() => {
// 	if (formData.value.before) {
// 		const label = beforeList.find(item => item.value == formData.value.before).label
// 		console.log("label", label)
// 		return label
// 	} else {
// 		return ''
// 	}
// })
const form = ref(null)

function fetch() {
	postFormAction(url.getPlan, {
		id: mainModel.value.id
	}).then((res) => {
		formData.value = res.data;
		setBeforeLabel()
		getPlanAttachmentListByPlanIdData()
		times.value = [formData.value.myDate, formData.value.endDate];

		formData.value.mine = formData.value.mine == 1 ? true : false;
		formData.value.others = formData.value.others == 1 ? true : false;
		formData.value.hadUsers = [];
		if (formData.value.distUsers) {
			isMultiDeptistUserRealNames.value = false;
			const realNames = formData.value['distUserRealNames'].split(',');
			const userNames = formData.value.distUsers.split(',');
			realNames.forEach((item, index) => {
				formData.value['hadUsers'].push({
					key: userNames[index],
					name: userNames[index],
					title: item,
					realName: item,
				});
			});
		} else {
			isMultiDeptistUserRealNames.value = true;
		}
		console.log("formData", formData.value)
	});
}
//获取附件
async function getPlanAttachmentListByPlanIdData() {
	const res = await postFormAction('/plan/attachment/listByPlanId', {
		planId: formData.value.id
	})
	console.log("getPlanAttachmentListByPlanIdData", res)
	const {
		data
	} = res
	if (data && data.length) {
		fileUploadRef.value.fileList = data
	}
}

//设置提醒时间的label
function setBeforeLabel() {
	formData.value.beforeName = ''
	if (formData.value.before) {
		formData.value.beforeName = beforeList.find(item => item.value == formData.value.before).label
	}
}
//回调时间
function handleConfirmTime(e) {
	const {
		value
	} = e
	if (value && value.length) {
		times.value = value
		formData.value.myDate = value[0]
		formData.value.endDate = value[1]
	}
	showTime.value = false
}
const showBeforeRef = ref(null)
//提醒时间打开
function handleShowBefore() {
	showBeforeRef.value._show()
}
//提醒时间回调
function handleConfirmBefore(e) {
	if (e && e.length) {
		formData.value.before = e[0].value
	}
	setBeforeLabel()
}
const selectUserRef = ref(null)
//选择人员
function handleSelectUser() {
	selectUserRef.value.open({
		users: formData.value['hadUsers']
	})
}
//选择用户回调
function handleSelectUserConfirm({
	selectUserList,
	label,
	value
}) {
	console.log("handleSelectUserConfirm", selectUserList)
	formData.value.distUserRealNames = label
	formData.value.distUsers = value
	if (Array.isArray(formData.value['hadUsers'])) {
		formData.value['hadUsers'] = formData.value['hadUsers'].concat(selectUserList)
	} else {
		formData.value['hadUsers'] = selectUserList
	}
}

//删除已选用户
function handleCloseTag(index) {
	formData.value['hadUsers'].splice(index, 1)
}
// 触发提交表单
function submit() {
	form.value.validate(async res => {
		console.log('验证通过', res, formData.value);
		try {
			if (!ishadSelect.value) {
				uni.showToast({
					title: '将日程分配给不能为空',
					icon: 'none',
					type: 'warning'
				});
				return;
			}
			let formDate = Object.assign({}, formData.value);
			formDate.shared = formDate.shared ? '1' : '0';
			formDate.isClosed = formDate.closed ? '1' : '0';
			formDate.mine = formDate.mine ? '1' : '0';
			formDate.others = formDate.others ? '1' : '0';

			formDate.distUsers = '';
			formDate.distUserRealNames = '';
			//保证最新的数据
			let distUserRealNames = []
			let distUsers = []
			if (formDate.hadUsers && formDate.hadUsers.length) {
				formDate.hadUsers.forEach(item => {
					distUserRealNames.push(item.title)
					distUsers.push(item.key)
				})
				formDate.distUsers = distUsers.join(',')
				formDate.distUserRealNames = distUserRealNames.join(',')
			}
			const fileList = fileUploadRef.value.fileList
			console.log('fileList', fileList);
			if (fileList && fileList.length) {
				formDate.attachments = fileList.map(item => item.id).join(',')
			}
			delete formDate.hadUsers;
			console.log('formDate', formDate);
			uni.showLoading({
				title: '保存中',
				mask: true
			})
			if (isUpdate.value == 1) {
				await postFormAction(url.update, formDate);
			} else if (isUpdate.value == 0) {
				await postFormAction(url.create, formDate);
			}
			close();
		} finally {
			uni.hideLoading()
		}
	}).catch(err => {
		console.log('err', err);
	})
}

function close() {
	var pages = getCurrentPages();
	// var currPage = pages[pages.length - 1]; //当前页面
	var prevPage = pages[pages.length - 2]; //上一个页面'
	console.log("prevPage", prevPage)
	if (prevPage.$vm && prevPage.$vm._ && prevPage.$vm._.exposeProxy) {
		prevPage.$vm._.exposeProxy.isRefresh = true
	}
	uni.navigateBack();
}

function updateTitle(title) {
	// 更新导航栏标题
	uni.setNavigationBarTitle({
		title,
	});
}


onLoad((options) => {
	console.log("options", options)
	mainModel.value = JSON.parse(options.record)
	isUpdate.value = Number(options.isUpdate)
	console.log("mainModel.value", mainModel.value)
	if (isUpdate.value == 1) {
		updateTitle('编辑')
		fetch()
	} else if (isUpdate.value == 0) {
		updateTitle('新增')
		formData.value.mine = true
		// formData.value.others = false
	} else {
		updateTitle('详情')
		fetch()
	}
})
onReady(() => {
	form.value.setRules(rules)
})
</script>

<style lang="scss" scoped>
.schedule_add_or_edit {
	padding: 20rpx;
	background-color: #fff;
}
</style>